import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { LibAppView } from "../../../../lib";
import { Card, App, Table, Button, Switch, Form, Input } from "antd";
import { AdvancedSearch } from "../../Component/AdvancedSearch";
import { FormattedMessage, useIntl } from "react-intl";
import { Edit } from "./Edit";
import { useTableData } from "../../hooks";
import { AdminRight } from "@/pages/Admin/data/AdminPageAuth";
import { ResourceList } from "../../Component/ResourceList";
import { useDelete } from "../../hooks/useDelete";
import { PlusOutlined } from "@ant-design/icons";

const UserList = LibAppView.withService()((props) => {
    const intl = useIntl();
    const app = LibAppView.useMicroApp();
    const { message, modal } = App.useApp();
   
    const listRef = useRef<any>();
    const deleteAction = useDelete({
            endPoint: "user.groupSubmit",
            cancelEndPoint: "user.groupSubmit",
            data: {},
            listRef
    });
    const SearchFields: Admin.IAdvancedField[] = [
        {
            type: "Input",
            label: "admin.pages.user.list.name",
            name: "loginName",
            placeholder: "admin.layout.input.placeholder",
            props: { autoComplete: "off" }
        },
        {
            type: "Input",
            label: "admin.pages.user.list.nickname",
            name: "userName",
            placeholder: "admin.layout.input.placeholder",
            props: { autoComplete: "off" }
        }
    ];
    
    
  
    const columns = useMemo(() => ([
        {
            title: <FormattedMessage id="admin.pages.user.list.name"/>,
            dataIndex: "loginName",
            width: 120,
            fixed: true
        },
        {
            title: <FormattedMessage id="admin.pages.user.list.nickname"/>,
            dataIndex: "userName",
            fixed: true,
            width: 200
        }, {
            title: "手机号码",
            dataIndex: "mobile",
            width: 100
        },{
            title: "科普单位",
            dataIndex: "company",
            width: 100
        }, {
            title: <FormattedMessage id="admin.pages.user.list.status"/>,
            dataIndex: "status",
            width: 80,
            render: (status: number, data: any) => {
                return <AdminRight authRight="editable" mode="disabled"><Switch
                    checkedChildren={<FormattedMessage id="admin.pages.operate.enabled"/>}
                    unCheckedChildren={<FormattedMessage id="admin.pages.operate.disabled"/>}
                    checked={status == 1}
                    onChange={(checked) => {
                        listRef.current.showLoading();
                        props.withServiceApi.send({
                            endPoint: "user.status",
                            data: {
                                id: data.id,
                                status: checked ? 1 : 0
                            }
                        }).then(() => {
                            listRef.current.refreshData();
                        }).catch((err) => {
                            listRef.current.hideLoading();
                            message.error(err.message || "未知错误");
                            console.error(err);
                        });
                    }}
                /></AdminRight>
            }
        }, {
            title: <FormattedMessage id="admin.pages.updateTime"/>,
            dataIndex: "updateDateTime",
            width: 120
        },{
            title: <FormattedMessage id="admin.pages.language.operate"/>,
            dataIndex: "id",
            width: 200,
            render: (id: number, data: any) => {
                return (<><AdminRight authRight="editable" mode="disabled">
                        <Button type="primary" size="small" onClick={() => {
                            app.startJourney("userManagement", { state: data });
                        }}>
                            <FormattedMessage id="admin.pages.operate.edit"/>
                        </Button>
                    </AdminRight>
                   
                    <AdminRight authRight="deleteable" mode="disabled">
                    <Button size="small" onClick={() => {
                         modal.confirm({
                            title: intl.formatMessage({id:"admin.layout.modal.question"}),
                            content: intl.formatMessage({id:"admin.pages.user.list.msg.delete"}),
                            okText: intl.formatMessage({id:"admin.layout.modal.confirm"}),
                            cancelText: intl.formatMessage({id:"admin.layout.modal.cancel"}),
                            onOk: () => {
                                listRef.current.showLoading();
                                props.withServiceApi.send({
                                    endPoint: "user.status",
                                    data: {
                                        id,
                                        status: -1
                                    }
                                }).then(() => {
                                    listRef.current.refreshData();
                                }).catch((err) => {
                                    message.error(err.message || "未知错误");
                                    console.error(err);
                                    listRef.current.hideLoading();
                                });
                            }
                         });
                    }}><FormattedMessage id="admin.pages.operate.delete"/></Button>
                    </AdminRight>
                    { data.loginRetryLimit && <AdminRight authRight="editable" mode="disabled">
                        <Button size="small" onClick={() => {
                            //deleteRetryLimit
                            listRef.current.showLoading();
                                props.withServiceApi.send({
                                    endPoint: "user.deleteRetryLimit",
                                    data: {
                                        username: btoa(data.loginName)
                                    }
                                }).then(() => {
                                    listRef.current.refreshData();
                                }).catch((err) => {
                                    message.error(err.message || "未知错误");
                                    console.error(err);
                                    listRef.current.hideLoading();
                                });
                        }}>
                            解除登录限制
                        </Button>
                    </AdminRight> }
                </>);
            }
        }
    ]),[]);
    const listEndPoint = useMemo(() => ({
            endPoint: "user.list"
    }), []);
    const Operator = useMemo(() => {
        return () => {
            return (<AdminRight authRight="editable" mode="disabled">
                <Button type="primary" onClick={() => {
                    app.startJourney("userManagement")
                }}>
                    <PlusOutlined />
                    <span><FormattedMessage id="admin.pages.operate.add" /></span>
                </Button>
            </AdminRight>);
        }
    }, []);
    useLayoutEffect(() => {
        app.registeJourney({
            name: "userManagement",
            title: "",
            stepJourney: true,
            isTempJourney: true,
            steps: [
                {
                    title: "admin.pages.operate.edit",
                    Component: Edit,
                    "isMemoryPage": true
                }
            ]
        });
    }, []);
     
    return (
          <ResourceList
            refApi={listRef}
            tableColumns={columns}
            searchFields={SearchFields} 
            listEndPoint={listEndPoint}
            Operators={Operator}
        />
    );
});

export default UserList;
